package mes.kanban.config;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * webservice 动态调用管理类
 * @author gjy
 *
 * 2018年1月25日下午2:45:14
 */
@Component
public class WebserviceConfig {
	
	
	private static final Logger log = LoggerFactory.getLogger(WebserviceConfig.class);

	public Object getMessageByWebService(String url,Class clazz) {
		
		JaxWsProxyFactoryBean soapFactoryBean = new JaxWsProxyFactoryBean();
		soapFactoryBean.setAddress(url);
		soapFactoryBean.setServiceClass(clazz);
		Object o = soapFactoryBean.create();
		
		return o;
		
	}
	
	
	/**
	 * 传入参数来进行远程调用
	 * @param url
	 * @param methodName
	 * @param params
	 * @return
	 */
	public Object[] getMessageByWebservice(String url,String methodName,Object...params) {
		
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
		
		Client client = dcf.createClient(url);
		
		 Object[] objects = new Object[0];
		 
		 try {
			 
			 log.info("开始调用服务.....................");
	        	// invoke("方法名",参数1,参数2,参数3....);
				objects = client.invoke(methodName, params);
				log.info("调用成功...............");
			} catch (Exception e) {
				log.error("调用失败.........."+e.getMessage());
				e.printStackTrace();
			}
		
		
		return objects;
		
	}
	
	/**
	 *  加密方式访问
	 * @param url
	 * @param methodName
	 * @param params
	 * @param username
	 * @param password
	 * @return
	 */
	public Object[] getMessageByWebservice(String username,String password,String url,String methodName,Object...params) {
		
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
		
		Client client = dcf.createClient(url);
		
		// 需要密码的情况需要加上用户名和密码
         client.getOutInterceptors().add(new ClientLoginInterceptor(username,password));
		
		 Object[] objects = new Object[0];
		 
		 try {
			 
			 log.info("开始调用服务.....................");
	        	// invoke("方法名",参数1,参数2,参数3....);
			 objects = client.invoke(methodName, params);
				log.info("调用成功...............");
			} catch (Exception e) {
				log.error("调用失败.........."+e.getMessage());
				e.printStackTrace();
			}
		
		
		return objects;
		
	}

}
